# 导入蓝图
from . import profile_blue
from flask import g, render_template, redirect, request, jsonify, current_app, session, abort
# 导入登录验证器
from info.utils.commons import get_user
# 导入相应状态码
from info.utils.response_code import RET
# 导入数据库实例
from info import db
# 导入七牛云存储
from info.utils.image_storage import storage
# 导入常量文件
from info import constants
# 导入数据库模型
from info.models import Category, News, User


@profile_blue.route('/user_info')
@get_user
def user_info():
    """
    加载个人信息业
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    data = {
        "user": user.to_dict()
    }
    return render_template("user/user.html", data = data)


@profile_blue.route("/user_base_info", methods=["GET", "POST"])
@get_user
def user_base_info():
    """
    修改个人信息
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    # 如果是get请求，加载模板页面
    if request.method == 'GET':
        temp = request.args
        data = {
            'user': user.to_dict()
        }
        return render_template('user/user_base_info.html', data=data)

    # 获取参数
    nick_name = request.json.get("nick_name")
    signature = request.json.get("signature")
    gender = request.json.get("gender")
    # 检查参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    if gender not in ["MAN", "WOMEN"]:
        return jsonify(errno=RET.PARAMERR, errmsg="性别范围错误")

    # 保存到用户
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender
    # 保存到数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="用户数据更新错误")
    # 讲session中的缓存更新
    session["nick_name"] = user.nick_name

    # 返回相应
    return jsonify(errno=RET.OK, errmsg="OK")

@profile_blue.route("/pic_info", methods=["GET", "POST"])
@get_user
def pic_info():
    """
    头像上传
    :return:
    """
    user=g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        data={
            "user": user.to_dict()
        }
        return render_template("user/user_pic_info.html", data=data)

    # 获取图片参数
    avatar = request.files.get("avatar")
    # print(avatar)
    # 判断参数是否存在
    if not avatar:
        return jsonify(reeno=RET.PARAMERR, errmsg="参数缺失")
    # 读取图片信息
    try:
        image_data = avatar.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(reeno=RET.PARAMERR, errmsg="参数格式错误")
    # 调用七牛云存储服务
    try:
        image_name = storage(image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(reeno=RET.THIRDERR, errmsg="图片上传错误")
    # 保存图片名称到mysql
    user.avatar_url = image_name
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存头像错误")
    # 拼接图片的绝对路径给前端
    avatar_url = constants.QINIU_DOMIN_PREFIX + image_name
    data = {
        'avatar_url':avatar_url
    }
    return jsonify(errno=RET.OK, errmsg="OK",data=data)

@profile_blue.route("/user_follow")
@get_user
def user_follow():
    """
    操作关注的作者
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    # 获取页数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1
    # 查询关注并分页
    follows = []
    current_page = 1
    total_page = 1
    try:
        paginate = user.followers.paginate(p, constants.USER_FOLLOWED_MAX_COUNT, False)
        follows = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_page.logger.error(e)
    print(follows)

    # 遍历
    follwed_list = []
    for follow_user in follows:
        follwed_list.append(follow_user.to_dict())
    data = {
        "follwed_list":follwed_list,
        "total_page": total_page,
        "current_page": current_page
    }
    # print(data)
    return render_template("user/user_follow.html", data= data)

@profile_blue.route("/user/pass_info",methods=["GET","POST"])
@get_user
def pass_info():
    """
    修改密码
    param1: old_password	string	是	旧密码
    param2: new_password	string	是	新密码
    :return:
        errno	int	是	错误码
        errmsg	string	是	错误信息
    """
    # 检查用户登录
    user=g.user
    if not user:
        return redirect("/")
    if request.method == "GET":
        return render_template("user/user_pass_info.html")

    # 接收参数
    old_password = request.json.get("old_password")
    new_password = request.json.get("new_password")

    # 检查参数
    if not all([old_password,new_password]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不完整")
    # 比较旧密码与用户的密码
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errrmsg="旧密码验证失败")
    user.password = new_password
    # 保存进数据库
    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="保存数据失败")
    return jsonify(errno=RET.OK, errmsg="OK")

@profile_blue.route("/collention", methods=["GET","POST"])
@get_user
def user_collention():
    """
    我的收藏
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    # if request.method == "GET":
    #     return render_template("user/user_collection.html")

    # 获取参数
    p = request.args.get("p",1)
    #　检查参数
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p=1

    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        # 获取分页信息
        collections = paginate.items
        # 获取当前页
        current_page = paginate.page
        # 获取总页数
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    # 收藏列表
    collection_list = []
    for new in collections:
        collection_list.append(new.to_dict())

    data = {
        "collention_list": collection_list,
        "total_page": total_page,
        "current_page": current_page
    }
    # print(data)
    return render_template("user/user_collection.html", data=data)

@profile_blue.route("/user/news_release", methods=["GET","POST"])
@get_user
def news_release():
    """
    实现用户发布新闻的功能
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    # 获取请求方法
    if request.method == "GET":
        categories = []
        # 查询新闻分类
        try:
            # 获取新闻分类
            categories = Category.query.filter(Category.name != "最新")
        except Exception as e:
            current_app.logger.error(e)
        # 定义存储列表
        categories_list = []
        for category in categories:
           categories_list.append(category.to_dict())
        # print(categories_list)
        data = {
            "categories_list":categories_list
        }
        return render_template("user/user_news_release.html", data = data)
    """
        URL：/user/news_release
        请求方式：POST
        传入参数：JSON格式
        参数
            参数名	类型	是否必须	参数说明
            title	string	是	新闻标题
            category_id	int	是	新闻分类_id
            digest	string	是	新闻摘要
            index_image	file	是	索引图片
            content	string	是	新闻内容
        返回类型：JSON
            参数名	类型	是否必须	参数说明
            errno	int	是	错误码
            errmsg	string	是	错误信息
    """
    # 获取参数
    title = request.form.get("title")
    category_id = request.form.get("category_id")
    digest = request.form.get("digest")
    index_image = request.files.get("index_image")
    content = request.form.get("content")
    # print(title)
    # print(category_id)
    # print(digest)
    # print(index_image)
    # print(content)
    # 判断数据是否有值
    if not all([title, digest, content, index_image, category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数有误")

    # 尝试获取图片
    try:
        index_image = index_image.read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="图片获取失败")

    # 将图片上传到云存储
    try:
        key = storage(index_image)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg="图片保存失败")

    # 保存新闻信息
    news = News()
    news.title = title
    news.source = "个人发布"
    news.digest = digest
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = user.id
    # 新闻审核状态
    news.status = 1

    # 保存新闻
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="新闻保存错误")

    return jsonify(errno=RET.OK, errmsg="新闻发布成功,正在审核")


@profile_blue.route("/user/news_list")
@get_user
def user_news_list():
    """
    用户新闻列表
    :return:
    """
    user = g.user
    if not user:
        return redirect("/")
    # 获取页数
    p = request.args.get("p",1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    news_li = []
    current_page = 1
    total_page = 1
    try:
        paginate = News.query.filter(News.user_id == user.id).paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        news_li = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_page.logger.error(e)

    # 遍历添加
    news_list = []
    for news in news_li:
        news_list.append(news.to_review_dict())

    data = {
        "news_list":news_list,
        "current_page":current_page,
        "total_page":total_page
    }
    # print(data)
    return render_template("user/user_news_list.html", data=data)


@profile_blue.route("/other_info")
@get_user
def other_info():
    """
    查看其他用户信息
    :return:
    """
    user = g.user
    #获取用户id
    user_id = request.args.get("id")
    if not user_id:
        abort(404)
    # 查看用户模型
    other = None
    try:
        other = User.query.get(user_id)
    except Exception as e:
        current_app.logger.error(e)

    if not other:
        abort(404)

    # 判断当前登录用户是否关注了此用户
    is_followed = False
    if g.user:
        if other.followers.filter(User.id == other.id).count() > 0:
            is_followed = True

    # 组织数据，并返回
    data = {
        "user_info": user.to_dict(),
        "other_info": other.to_dict(),
        "is_followed": is_followed
    }
    return render_template("user/other.html", data = data)


@profile_blue.route("/logout", methods=['POST'])
def logout():
    """
    清除session中的对应登录之后保存的信息
    :return:
    """
    session.pop('user_id', None)
    session.pop('nick_name', None)
    session.pop('mobile', None)
    session.pop('is_admin', None)

    # 返回结果
    return jsonify(errno=RET.OK, errmsg="OK")

